<?php

namespace App\Http\Middleware;


use App\Helpers\RestUtils;
use Closure;
use \Illuminate\Http\Request;

/**
 * @author qfh
 */
class ValidateMiddleware
{

    /**
     * This namespace is applied to the controller routes in your routes file.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
     * @var string
     */
    protected $namespace = 'App\Http\Validators';

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $validator = null)
    {
//        $apiVersion = $request->segment(1);
        $request->flash();
//        $request->session()->reflash();
        if ($validator)
        {
            $request->flash();


            $validator = $this->namespace . '\\' . studly_case($validator) . 'Validator';
            $validator = new $validator($request->all());

            if (!$validator->passes())
            {
                $request->flash();
                return redirect()->back()->withErrors($validator->errors());
            }
        }
//        if ($validator)
//        {
//            $validator = $this->namespace . '\\' . studly_case($validator) . 'Validator';
//
//            $validator = new $validator;
//            $validat =  validator($request->all(),$validator->rules,$validator->messages);
//
//            if (!$validat)
//            {
//
//                return $validat;
//            }
//        }
        return $next($request);
    }

    public function terminate($request, $response)
    {
        // 请求结束干的事情..
    }

}
